package com.hzit.security.service;

import com.hzit.security.entity.User;
import com.hzit.security.exption.UsernamePasswordException;
import com.hzit.security.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class MyUserDetailService implements UserDetailsService {
	@Autowired
	private UserMapper userMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		//1.  根据用户名查询用户是否存在
		User user = userMapper.selectByPrimaryKey(username);        // 我们在数据库中设置username字段与id字段的值是一样的
		if(user == null){
			throw new UsernameNotFoundException("用户名输入有误！");
		}
		//2. 根据登录用户名,查询出用户的权限串列表
		List<String> permissionList = userMapper.findPermissionsByUsername(username);
		//3. 将角色列表放到authorities集合中
		Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
		for (String s : permissionList) {
			authorities.add(new SimpleGrantedAuthority(s));
		}
		for (String s : permissionList) {
			//因为源码中将关于角色的都添加了前缀ROLE_,所以我们在比较时也要添加这个前缀后才能比较得到结果
			authorities.add(new SimpleGrantedAuthority("ROLE_" + s));
		}
		System.out.println("permissionList = " + permissionList);
		return new org.springframework.security.core.userdetails.User(username,user.getPassword(),authorities);
	}
}
